#include "cm_collectionitem.h"

CM_CollectionItem::CM_CollectionItem(void)
{
}

CM_CollectionItem::~CM_CollectionItem(void)
{
}

int 
CM_CollectionItem::saveCollectionTime(int computerId)
{
    try {
		sqlite3_connection con(DEFAULT_DATABASE_NAME.c_str());
		sqlite3_transaction trans(con);
		{
			sqlite3_command cmd(con, "insert into collectionTime values(NULL ,?,?);");
			cmd.bind(1,computerId);
			cmd.bind(2,"currenttime()");
			cmd.executenonquery();
		}
		trans.commit();
		con.close();
	}
	catch(exception &ex) {
		cerr << "Exception Occured: saveCollectionTime() " << ex.what() << endl;
        return 0;
	}

    return getCollectionLastId(computerId);
}

int 
CM_CollectionItem::getCollectionLastId(int computerId)
{
    int collectionId = -1;
    try {
		sqlite3_connection con(DEFAULT_DATABASE_NAME.c_str());
		{
			sqlite3_command cmd(con, "select max(collectiontime_id) from collectionTime where computer_id=?; ");
            cmd.bind(1, computerId);
			sqlite3_reader reader = cmd.executereader();
			
			if(reader.read())
            {
				collectionId = reader.getint(0);				
			}
		}

		con.close();
	}
	catch(exception &ex) {
        cerr << "Exception Occured: getCollectionLastId() " << ex.what() << endl;        
		return 0;
	}
    
    return collectionId;
}

int 
CM_CollectionItem::getCollectionBeforeLastId(int computerId)
{
    int collectionId = -1;
    try {
		sqlite3_connection con(DEFAULT_DATABASE_NAME.c_str());
		{
            string query = "SELECT collectiontime_id FROM  collectionTime "
                "WHERE computer_id=? ORDER BY collectiontime_id DESC; ";
			sqlite3_command cmd(con, query);
            cmd.bind(1, computerId);
			sqlite3_reader reader = cmd.executereader();
			int counter = 0;
			while(reader.read())
            {
				collectionId = reader.getint(0);
                counter++;
                
                if(counter == 2)
                {
                    return collectionId;
                }
			}           
		}

		con.close();
	}
	catch(exception &ex) {
        cerr << "Exception Occured: getCollectionLastId() " << ex.what() << endl;        
		return 0;
	}
    
    return collectionId;
}